package 剑指offer;

public class 顺时针打印矩阵 {

    public int[] spiralOrder(int[][] matrix) {
        int m = matrix.length;
        if (m==0)
            return new int[0];
        int n = matrix[0].length;
        int[] ints = new int[m * n];
        int index=0;
        int left=0,right=n-1,top=0,bottom=m-1;
        while (true){
            //从左到右
            for (int i = left; i <=right ; i++) {
                ints[index++]=matrix[top][i];
            }
            if (++top>bottom)
                break;
            //从上到下
            for (int i = top; i <=bottom ; i++) {
                ints[index++]=matrix[i][right];
            }
            if (--right<left)
                break;
            //从右到左
            for (int i = right; i >=left ; i--) {
                ints[index++]=matrix[bottom][i];
            }
            if (--bottom<top)
                break;
            //从下到上
            for (int i = bottom; i >=top ; i--) {
                ints[index++]=matrix[i][left];
            }
            if (++left>right)
                break;
        }
        return ints;
    }
}
